<template>
  <!-- 安全专家管理 -->
  <base-breadcrumb :title="$route.meta.title">
    <searchData :searchData="searchArr" @search="search"></searchData>
    <a-card :bordered="false">
      <a-row :gutter="10">
        <!-- 树搜索 -->
        <a-col :span="4">
          <!-- <title-name title="安全专家管理"></title-name> -->
          <!-- 搜索专家委员会 -->
          <div class="mb12">
            <a-input-search
              :maxLength="30"
              v-model="keyword"
              class="mb12"
              placeholder="请输入"
              style="width: 100%"
              @change="onSearch"
            />
            <!-- 树节点 -->
            <a-spin
              v-if="(expertList && expertList.length > 0) || spinning"
              :spinning="spinning"
              :style="[{ height: treeHeight, minHeight: '200px', overflow: 'auto', width: '100%' }]"
            >
              <a-tooltip placement="left" v-for="item in expertList" :key="item.id">
                <template v-if="item.name.length > 16" slot="title">{{ item.name }}</template>
                <a-button
                  :type="currentExpert == item.id ? 'primary' : 'default'"
                  class="mb12"
                  block
                  @click="
                    currentExpert = item.id
                    search()
                  "
                >
                  <ellipsis :length="16">{{ item.name }}</ellipsis>
                  <span class="del_btn" v-if="item.status == 0">(停用)</span>
                </a-button>
              </a-tooltip>
            </a-spin>
            <empty v-else description="暂无安全委员会信息" />
          </div>
          <!-- 树操作栏 -->
          <div ref="btnBox" align="center">
            <a-button size="small" class="btn_right" type="primary" @click="handleOperate(0)">添加</a-button>
            <a-button size="small" :disabled="!currentExpert" class="btn_right" type="primary" @click="handleOperate(1)"
              >编辑</a-button
            >
            <a-button
              size="small"
              :type="activeItem && activeItem.status == 0 ? 'primary' : 'danger'"
              :disabled="!currentExpert"
              @click="handleStopNode"
              >{{ activeItem && activeItem.status == 0 ? '启用' : '停用' }}</a-button
            >
          </div>
        </a-col>
        <!-- 表格头部 -->
        <a-col :span="20">
          <a-row type="flex" justify="space-between" align="middle">
            <title-name :title="expertTitle"></title-name>
            <!-- 操作栏 -->
            <div class="mb12">
              <a-button :disabled="!currentExpert" icon="plus" class="btn_right" type="primary" @click="visible = true"
                >添加人员</a-button
              >
              <a-button
                :disabled="rowSelection.selectedRowKeys.length == 0"
                icon="delete"
                type="danger"
                @click="handleRemoveMore"
                >移除</a-button
              >
            </div>
          </a-row>
          <!-- 统计选中项 -->
          <a-alert :showIcon="true">
            <template slot="message">
              <span style="margin-right: 12px">
                已选择:
                <a>
                  <b>{{ rowSelection.selectedRowKeys.length }}</b>
                </a>
                项
              </span>
            </template>
          </a-alert>
          <!-- 表格 -->
          <!-- :style="[{height:boxHeight,minHeight:'250px',overflow:'auto'}]" -->
          <list-table
            ref="table"
            size="default"
            rowKey="id"
            :columns="columns"
            :request="loadData"
            :row-selection="rowSelection"
            showPagination="auto"
          >
            <!-- 表格行操作栏 -->
            <span slot="action" slot-scope="text, record">
              <template>
                <a @click="handleManage(record)">查看</a>
                <a-divider type="vertical" />
                <a
                  @click="
                    result = record
                    visibleHistory = true
                  "
                  >上课</a
                >
                <a-divider type="vertical" />
                <a
                  @click="
                    result = record
                    visibleResult = true
                  "
                  >移除</a
                >
              </template>
            </span>
            <a-list
              slot="expandedRowRender"
              slot-scope="record"
              item-layout="horizontal"
              :data-source="formatItem(record)"
            >
              <a-list-item slot="renderItem" slot-scope="item">
                <div>{{ item }}</div>
              </a-list-item>
            </a-list>
          </list-table>
        </a-col>
      </a-row>
    </a-card>
    <!-- 添加专家库人员表单弹窗 -->
    <dialog-edit
      ref="dialogEdit"
      headerTitle="添加专家库人员"
      :visible.sync="visible"
      :api="api"
      :form="{ expertGroupId: currentExpert }"
      @confirm="submitForm"
    ></dialog-edit>
    <!-- 添加/编辑专家库人员表单弹窗 -->
    <dialog-expert
      ref="dialogExpert"
      :headerTitle="['新增专家组', '编辑专家组'][editModel]"
      :visible.sync="visibleNode"
      :form="formNode"
      :editModel="editModel"
      @confirm="submitNodeForm"
    ></dialog-expert>
    <!-- 添加上课历史表单弹窗 -->
    <dialog-history
      ref="dialogHistory"
      headerTitle="新增上课历史"
      :visible.sync="visibleHistory"
      :form="result"
      @confirm="submitHistoryForm"
      :width="700"
    ></dialog-history>
    <!-- 移除提示框 -->
    <result :visible.sync="visibleResult" :form="form">
      <template #title>
        <p style="color: #000">警告提示</p>
      </template>
      <template #subTitle>
        <p style="color: #000">是否确认将选中员工从专家库中移除</p>
      </template>
      <template #extra>
        <a-button :loading="loading" @click="handleRemove" type="danger">移除</a-button>
        <a-button @click="visibleResult = false" type="primary">取消</a-button>
      </template>
    </result>
  </base-breadcrumb>
</template>

<script>
import dialogExpert from '@/views/quality/securityPerson/expert/dialogExpert.vue' // 表单弹窗
import dialogHistory from '@/views/quality/securityPerson/expert/dialogHistory.vue' // 表单弹窗
import dialogEdit from '@/views/quality/securityPerson/employees/dialogEdit.vue' // 表单弹窗
import { STable, Ellipsis } from '@/components' // 表格
import { expert, group, employees, lesson } from '@/api/quality/safe' // api
import Result from '@/components/Dialog/Result' // 提示
import { Empty } from 'ant-design-vue' // 无数据提示
import cloneDeep from 'lodash.clonedeep' // 深拷贝

const searchArr = [
  // 搜索框
  {
    name: '员工名称',
    value: 'employeeName',
    type: 'input',
  },
  {
    name: '员工编号',
    value: 'employeeNo',
    type: 'input',
  },
  {
    name: '状态',
    value: 'status',
    type: 'select',
    data: [
      {
        value: '0',
        label: '离职',
      },
      {
        value: '1',
        label: '在职',
      },
    ],
  },
  {
    name: '电话号码',
    value: 'phone',
    type: 'input',
  },
]
const columns = [
  {
    title: '员工名称',
    dataIndex: 'employeeName',
    width: 100,
    ellipsis: true,
  },
  {
    title: '员工编号',
    width: 120,
    ellipsis: true,
    dataIndex: 'employeeNo',
  },
  {
    title: '所在部门',
    dataIndex: 'dept',
    width: 120,
    ellipsis: true,
  },
  {
    title: '电话号码',
    dataIndex: 'phone',
    width: 120,
  },
  {
    title: '职务',
    dataIndex: 'post',
    width: 120,
    ellipsis: true,
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 80,
  },
  // {
  //   title: '最高学历专业',
  //   dataIndex: 'specialitieMax',
  //   width: '120px',
  // },
  {
    title: '操作',
    dataIndex: 'action',
    // fixed: 'right',
    width: '180px',
    scopedSlots: { customRender: 'action' },
  },
]
export default {
  name:'a'+ Date.now(),
  components: {
    STable,
    dialogEdit,
    dialogExpert,
    dialogHistory,
    Result,
    Empty,
    Ellipsis,
  },
  computed: {
    // 选中专家项
    activeItem() {
      let list = cloneDeep(this.expertList).filter((item) => item.id == this.currentExpert)
      return list && list.length > 0 ? list[0] : ''
    },
    //筛选列表
    expertList() {
      // 根据关键词筛选列表
      let list = cloneDeep(this.expertAll).filter((item) => {
        return item.name ? item.name.indexOf(this.keyword) != -1 : false
      })
      // 筛选列表是否和选中值有对应项
      let currentExpert = list.every((item) => {
        return item.id != this.currentExpert
      })
      // 若没有对应项且筛选列表不为空，则默认选中第一项
      if (currentExpert && list.length > 1) {
        this.currentExpert = list[0].id
      }
      return list
    },
    // 树节点api
    api() {
      return employees
    },
    // 表格列表请求参数
    args() {
      let args = this.queryParam
      // 添加树节点id
      if (this.currentExpert) {
        args.expertGroupId = this.currentExpert
      }
      return args
    },
    expertTitle() {
      let currentExpert = this.currentExpert
      let list = cloneDeep(this.expertList).filter((item) => item.id == currentExpert)
      let title = list.length > 0 ? list[0].name : '请选择安全专家'
      return title
    },
  },
  data() {
    this.columns = columns
    this.searchArr = searchArr
    return {
      loading: false,
      keyword: '', // 专家委员会关键词
      expertAll: [], // 专家委员会原始列表
      currentExpert: '', // 当前专家类别
      spinning: false, // 专家委员会加载控件
      visibleResult: false, // 移除结果弹窗控件
      visibleNode: false, // 节点弹窗控件
      visibleHistory: false, // 上课历史弹窗控件
      // 操作类型：0 添加 1 编辑 3 查看
      editModel: 0,
      // 责任区域弹窗控件
      visible: false,
      // 表格复选框配置
      rowSelection: {
        selectedRowKeys: [],
        onChange(selectedRowKeys) {
          this.selectedRowKeys = selectedRowKeys
        },
      },
      selectedKeys: [], // 选中节点
      selectOptions: {}, // 选中节点对象
      // 弹窗参数
      form: null,
      // 弹窗参数
      formNode: {},
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        let that = this
        if (!that.currentExpert) {
          return false
        }
        const requestParameters = Object.assign({}, parameter, that.args)
        return expert.getList(requestParameters).then((res) => {
          that.$refs.table.clearSelected()
          return res
        })
      },
      result: {}, // 查看参数对象
      boxHeight: 0, // 盒子高度
      treeHeight: 0, // 专家组高度
    }
  },
  mounted() {
    let that = this
    // 初始化
    that.getExpert()
  },
  methods: {
    // 深拷贝
    cloneDeep,
    formatItem(e) {
      let datas = []
      let title = { time: '入组时间：' }
      // let title = { company: '所属公司：', branch: '所属分公司：', projectDept: '所属项目部：', time: '入组时间：' }
      for (let index in e) {
        let item = e[index]
        for (let i in title) {
          if (i == index) {
            datas.push(title[i] + (e[index] || '暂无'))
          }
        }
      }
      return datas
    },
    // 停启用
    handleStopNode() {
      let that = this
      let e = cloneDeep(this.expertList).filter((item) => item.id == this.currentExpert)[0]
      let enabled = e.status == 1 ? '停用' : '启用'
      that.$confirm({
        title: '温馨提示',
        content: `确认${enabled}？`,
        okText: '提交',
        cancelText: '关闭',
        onOk() {
          return group.switchStatus(e).then((res) => {
            // if (res.code == 200 || res.data.code == 200) {
            e.enabled = !e.enabled
            that.$message.success(enabled + '成功！')
            that.getExpert()
            // } else {
            //   that.$message.warning(enabled + '失败！')
            // }
          })
        },
      })
    },
    // 获取专家委员会列表且初始化表格列表
    getExpert() {
      let that = this
      that.spinning = true
      group
        .getList()
        .then((res) => {
          that.spinning = false
          if (res.code == 200) {
            that.expertAll = cloneDeep(res.data)
            if (that.currentExpert) {
              that.search()
            } else {
              if (res.data.length > 0) {
                that.currentExpert = res.data[0].id
                that.search()
              }
            }
          }
        })
        .catch((res) => {
          that.spinning = false
        })
    },
    // 头部搜索
    search(value) {
      // 赋值表单
      if (value) {
        this.queryParam = value
      }
      this.$refs.table.refresh(true)
    },
    onSearch() {},
    // 提交节点表单
    submitNodeForm(e) {
      let that = this
      let name = ['create', 'update'][that.editModel] // 根据操作切换url地址
      group[name](e)
        .then((res) => {
          that.$refs.dialogExpert.loading = false
          // if (res.code == 200 || res.data.code) {
          that.$message.success(['添加', '编辑'][that.editModel] + '成功！')
          that.getExpert()
          that.visibleNode = false
          // } else {
          //   that.$message.warning(['编辑', '添加'][that.editModel] + '失败！')
          // }
        })
        .catch((res) => {
          that.$refs.dialogExpert.loading = false
        })
    },
    // 提交上课历史表单
    submitHistoryForm(e) {
      let that = this
      lesson
        .update(e)
        .then((res) => {
          that.$refs.dialogHistory.loading = false
          // if (res.data.code == 200 || res.code == 200) {
          that.$message.success('添加成功！')
          that.search()
          that.visibleHistory = false
          // } else {
          //   that.$message.warning('添加失败！')
          // }
        })
        .catch((res) => {
          that.$refs.dialogHistory.loading = false
        })
    },
    // 提交专家组表单
    submitForm(e) {
      let that = this
      let args = {
        expertGroupId: that.currentExpert,
        securityEmployees: e,
      }
      that.$confirm({
        title: '温馨提示',
        content: '确认添加？',
        okText: '提交',
        cancelText: '关闭',
        onOk() {
          return expert.create(args).then((res) => {
            // if (res.data.code == 200 || res.code == 200) {
            that.$message.success('添加成功！')
            that.$refs.dialogEdit.search()
            that.search()
            // that.visible = false
            // } else {
            //   that.$message.warning('添加失败！')
            // }
          })
        },
      })
    },
    // 移除表格选中项
    handleRemoveMore() {
      // 若有选中项
      // if (this.rowSelection.selectedRowKeys.length > 0) {
      this.result = {}
      this.visibleResult = true
      // } else {
      //   this.$message.warning('请选中人员后再操作！')
      // }
    },
    // 提交移除表单
    handleRemove() {
      let that = this
      let result = that.result // 点击的行对象
      let ids = [] // 请求参数
      // 配置请求参数，单个或者多选
      if (result.id) {
        ids.push(result.id)
      } else {
        ids = that.rowSelection.selectedRowKeys
      }
      // 按钮加载中，防止重复提交
      that.loading = true
      // 提交移除表单
      expert
        .remove({ ids: ids, expertGroupId: that.currentExpert })
        .then((res) => {
          // 按钮加载结束
          that.loading = false
          // if (res.data.code == 200) {
          that.$message.success('移除成功！')
          // 重置列表
          that.$refs.table.loadData()
          that.visibleResult = false
          // 关闭提示弹窗
          // } else {
          //   that.$message.warning('移除失败！')
          // }
        })
        .catch((res) => {
          that.loading = false
        })
    },
    // 查看
    handleManage(b) {
      b.isExpert = true
      this.$router.push({
        name: 'expertEdit',
        query: { id: b.id },
      })
    },
    // 专家委员会操作
    handleOperate(e) {
      this.editModel = e
      this.formNode = e != 0 ? this.expertList.filter((item) => item.id == this.currentExpert)[0] : {}
      this.visibleNode = true
    },
  },
}
</script>

